from pprint import pprint as P
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


def main(read_file_name, time_dimension):
    with open(read_file_name) as f:
        data = [i.strip() for i in f.readlines()]
    for td in time_dimension:
        time_function_processing_set = {
            'hour': lambda x: x[:13] + ":00:00",
            'day': lambda x: x[:10] + " 00:00:00",
            'month': lambda x: x[:7] + ".01 00:00:00",
            'year': lambda x: x[:4] + ".01.01 00:00:00",
        }
        with open(read_file_name) as f:
            rows = list(
                map(lambda x: [time_function_processing_set[td](x[0]),
                               float(x[1]), float(x[2]), float(x[3]), float(x[4]), float(x[5])],
                    map(lambda x: x.split(','),
                        filter(lambda x: 'Time' not in x,
                               data))))
        rows = np.array(rows)
        df = pd.DataFrame(rows, columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume'])

        result = []
        for _, group in df.groupby('Time'):
            row = group.to_numpy()
            result.append([
                row[0][0],
                round(float(row[0][1]), 4),
                round(max(row[:, 2].astype(np.float)), 4),
                round(min(row[:, 3].astype(np.float)), 4),
                round(float(row[-1][4]), 4),
                round(sum(row[:, 5].astype(np.float)), 4)
            ])

        np_result = np.array(result)
        pd.DataFrame(np_result, columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume']
                     ).to_csv(read_file_name.replace('.', '_')+'.csv.'+td, index=False, encoding='utf_8_sig')


if __name__ == "__main__":
    main("XAUUSD.txt", ['hour', 'day', 'month', 'year'])
